package com.platform.api;

import com.alibaba.fastjson.JSONObject;
import com.platform.annotation.LoginUser;
import com.platform.entity.*;
import com.platform.service.ApiAgentService;
import com.platform.service.ApiUserDeptService;
import com.platform.service.ApiUserService;
import com.platform.service.SysConfigService;
import com.platform.util.ApiBaseAction;
import com.platform.util.CommonUtil;
import com.platform.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * 作者: @author Harmon <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@Api(tags = "会员验证")
@RestController
@RequestMapping("/api/user")
public class ApiUserController extends ApiBaseAction {
    @Autowired
    private ApiUserService userService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private ApiUserDeptService userDeptService;
    @Autowired
    private ApiAgentService agentService;

    /**
     * 发送短信
     */
    @ApiOperation(value = "发送短信")
    @PostMapping("smscode")
    public Object smscode(@LoginUser UserVo loginUser) {
        JSONObject jsonParams = getJsonRequest();
        String phone = jsonParams.getString("phone");
        // 一分钟之内不能重复发送短信
        SmsLogVo smsLogVo = userService.querySmsCodeByUserId(loginUser.getUserId());
        if (null != smsLogVo && (System.currentTimeMillis() / 1000 - smsLogVo.getLog_date()) < 1 * 60) {
            return toResponsFail("短信已发送");
        }
        //生成验证码
        String sms_code = CharUtil.getRandomNum(4);
        String msgContent = "您的验证码是：" + sms_code + "，请在页面中提交验证码完成验证。";
        // 发送短信
        String result = "";
        //获取云存储配置信息
        SmsConfig config = sysConfigService.getConfigObject(Constant.SMS_CONFIG_KEY, SmsConfig.class);
        if (StringUtils.isNullOrEmpty(config)) {
            return toResponsFail("请先配置短信平台信息");
        }
        if (StringUtils.isNullOrEmpty(config.getName())) {
            return toResponsFail("请先配置短信平台用户名");
        }
        if (StringUtils.isNullOrEmpty(config.getPwd())) {
            return toResponsFail("请先配置短信平台密钥");
        }
        if (StringUtils.isNullOrEmpty(config.getSign())) {
            return toResponsFail("请先配置短信平台签名");
        }
        try {
            /**
             * 状态,发送编号,无效号码数,成功提交数,黑名单数和消息，无论发送的号码是多少，一个发送请求只返回一个sendid，如果响应的状态不是“0”，则只有状态和消息
             */
            result = SmsUtil.crSendSms(config.getName(), config.getPwd(), phone, msgContent, config.getSign(),
                    DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "");
        } catch (Exception e) {

        }
        String arr[] = result.split(",");

        if ("0".equals(arr[0])) {
            smsLogVo = new SmsLogVo();
            smsLogVo.setLog_date(System.currentTimeMillis() / 1000);
            smsLogVo.setUser_id(loginUser.getUserId());
            smsLogVo.setPhone(phone);
            smsLogVo.setSms_code(sms_code);
            smsLogVo.setSms_text(msgContent);
            userService.saveSmsCodeLog(smsLogVo);
            return toResponsSuccess("短信发送成功");
        } else {
            return toResponsFail("短信发送失败");
        }
    }
    /**
     * 发送短信
     */
    @ApiOperation(value = "支付成功短信")
    @RequestMapping("paysuccess")
    public Object paysuccess(@LoginUser UserVo loginUser) {
        JSONObject jsonParams = getJsonRequest();
        String phone = jsonParams.getString("phone");
        String orderSn = jsonParams.getString("orderSn");
        // 一分钟之内不能重复发送短信
        SmsLogVo smsLogVo = userService.querySmsCodeByUserId(loginUser.getUserId());
        if (null != smsLogVo && (System.currentTimeMillis() / 1000 - smsLogVo.getLog_date()) < 1 * 60) {
            return toResponsFail("短信已发送");
        }
        String sms_code = CharUtil.getRandomNum(4);
        String msgContent = "尊敬的客户，您的订单号为：" +orderSn  + " 的商品已经支付成功，请注意物流信息。";
        // 发送短信
        String result = "";
        //获取云存储配置信息
        SmsConfig config = sysConfigService.getConfigObject(Constant.SMS_CONFIG_KEY, SmsConfig.class);
        if (StringUtils.isNullOrEmpty(config)) {
            return toResponsFail("请先配置短信平台信息");
        }
        if (StringUtils.isNullOrEmpty(config.getName())) {
            return toResponsFail("请先配置短信平台用户名");
        }
        if (StringUtils.isNullOrEmpty(config.getPwd())) {
            return toResponsFail("请先配置短信平台密钥");
        }
        if (StringUtils.isNullOrEmpty(config.getSign())) {
            return toResponsFail("请先配置短信平台签名");
        }
        try {
            /**
             * 状态,发送编号,无效号码数,成功提交数,黑名单数和消息，无论发送的号码是多少，一个发送请求只返回一个sendid，如果响应的状态不是“0”，则只有状态和消息
             */
            result = SmsUtil.crSendSms(config.getName(), config.getPwd(), phone, msgContent, config.getSign(),
                    DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "");
        } catch (Exception e) {

        }
        String arr[] = result.split(",");

        if ("0".equals(arr[0])) {
            smsLogVo = new SmsLogVo();
            smsLogVo.setLog_date(System.currentTimeMillis() / 1000);
            smsLogVo.setUser_id(loginUser.getUserId());
            smsLogVo.setPhone(phone);
            smsLogVo.setSms_code(sms_code);
            smsLogVo.setSms_text(msgContent);
            userService.saveSmsCodeLog(smsLogVo);
            return toResponsSuccess("短信发送成功");
        } else {
            return toResponsFail("短信发送失败");
        }
    }

    /**
     * 发送模板消息
     */
    @ApiOperation(value = "发送模板消息")
    @RequestMapping("sendTemplateMsg")
    public Object sendTemplateMsg(@LoginUser UserVo loginUser) {
        JSONObject jsonParams = getJsonRequest();
        String openId = jsonParams.getString("openId");
        String formId = jsonParams.getString("formId");
        String templateId = jsonParams.getString("templateId");
        JSONObject data=jsonParams.getJSONObject("data");
        String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxda32b8b81ad14f98&secret=375c3cc71ea3d11cde3bdf999cfbac87";
        JSONObject jsonobject= CommonUtil.httpsRequest(token_url,"GET","");
        String accesstoken = jsonobject.getString("access_token");


        String sendurl="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+accesstoken;
        JSONObject dataInfo = new JSONObject();
        dataInfo.put("access_token",accesstoken);
        dataInfo.put("touser",openId);
        dataInfo.put("form_id",formId);
        dataInfo.put("template_id",templateId);
        dataInfo.put("page","pages/ucenter/order/order");
        dataInfo.put("data",data);
        JSONObject obj=CommonUtil.httpsRequest(sendurl,"POST",dataInfo.toString());
        if(obj.getString("errcode").equals("0"))
            return toResponsSuccess("发送成功成功");
        else return toResponsFail("发送模板消息失败");
    }

    /**
     * 获取当前会员等级
     *
     * @param loginUser
     * @return
     */
    @ApiOperation(value = "获取当前会员等级")
    @PostMapping("getUserLevel")
    public Object getUserLevel(@LoginUser UserVo loginUser) {
        String userLevel = userService.getUserLevel(loginUser);
        return toResponsSuccess(userLevel);
    }

    /**
     * 绑定手机
     */
    @ApiOperation(value = "绑定手机")
    @PostMapping("bindMobile")
    public Object bindMobile(@LoginUser UserVo loginUser) {
        JSONObject jsonParams = getJsonRequest();
        SmsLogVo smsLogVo = userService.querySmsCodeByUserId(loginUser.getUserId());

        String mobile_code = jsonParams.getString("mobile_code");
        String mobile = jsonParams.getString("mobile");

        if (!mobile_code.equals(smsLogVo.getSms_code())) {
            return toResponsFail("验证码错误");
        }
        UserVo userVo = userService.queryObject(loginUser.getUserId());
        userVo.setMobile(mobile);
        userService.update(userVo);
        return toResponsSuccess("手机绑定成功");
    }

    /**
     * 我要开店
     */
    @ApiOperation(value = "我要开店")
    @PostMapping("applyOpenShop")
    public Object applyOpenShop(String myShopName, Integer myShopType, @LoginUser UserVo loginUser) {
        int exist = userDeptService.countByDeptName(myShopName);
        if (exist > 0) {
            return toResponsFail("该名称已被使用");
        }

        UserDeptVo vo = userDeptService.applyOpenShop(loginUser.getUserId(), myShopName, myShopType);

        return toResponsSuccess(vo);
    }

    /**
     * 检测是否已开店
     */
    @ApiOperation(value = "检测是否已开店")
    @PostMapping("queryOpenShop")
    public Object queryOpenShop(@LoginUser UserVo loginUser) {
        List<UserDeptVo> shops = userDeptService.queryOpenShop(loginUser.getUserId());
        if(shops != null && shops.size() > 0){
            return toResponsSuccess(shops.get(0));
        }
        else{
            return toResponsFail("未开店");
        }
    }

    @ApiOperation(value = "申请成为代理商")
    @PostMapping("applyAgent")
    public Object applyAgent(@LoginUser UserVo loginUser, Long vendorRootDeptId, Long agentRootDeptId, Integer applyAgentUserGrade) {
        AgentVo vo = agentService.applyAgent(vendorRootDeptId, agentRootDeptId, loginUser.getUserId(), applyAgentUserGrade);

        if(vo != null){
            return toResponsSuccess(vo);
        }
        else{
            return toResponsFail("不能重复申请！");
        }
    }

    @ApiOperation(value = "检查是否有申请代理记录状态")
    @PostMapping("checkAgentApplyStatus")
    public Object checkAgentApplyStatus(Long vendorRootDeptId, Long agentRootDeptId) {
        //0表示无申请，1表示已提交申请但未通过，2表示申请已通过
        List<AgentVo> list = agentService.getAgentApplyByVendorAndAgent(vendorRootDeptId, agentRootDeptId);
        if(list != null && list.size() > 0){
            if(list.get(0).getIsCert().intValue() == 1){
                return toResponsSuccess(2);
            }
            else {
                return toResponsSuccess(1);
            }
        }
        else{
            return toResponsSuccess(0);
        }
    }
}